# TypeScript
TypeScript (opens new window) 是具有类型语法的 JavaScript。
# 一、类型系统
JavaScript (opens new window) 定义了 8 种内置类型,TypeScript (opens new window) 为内置类型提供了相应的基元类型。
# 基础类型
# 原始类型
-
let isDone: boolean = false; -
let decLiteral: number = 6; let hexLiteral: number = 0xf00d; let binaryLiteral: number = 0b1010; let octalLiteral: number = 0o744; -
let name: string = "bob"; -
void类型表示没有任何类型,常用于表示函数没有返回值。function warnUser(): void { console.log("This is my warning message"); }
# 特殊类型
-
TypeScript 中的一个逃逸类型,可以绕过类型检查系统,因此不会对值进行任何类型检查。
let notSure: any = 4; notSure = "maybe a string instead"; notSure = false; -
unknown类型也表示不确定的类型,但与any不同,它是类型安全的。当一个值声明为
unknown类型时,必须在使用它之前先进行类型检查或类型断言,以告诉 TypeScript 它的确切类型。let notSure: unknown = 4; notSure = "maybe a string instead"; notSure = false;
# 空类型
-
never类型表示永不存在的值的类型,常用于表示会抛出异常的函数的返回值。function error(message: string): never { throw new Error(message); }
# 对象类型
# 基础对象
-
object表示非原始类型,也就是除number,string,boolean,symbol,null或undefined之外的类型。let obj: object = { name: "John", age: 30 };通常不直接使用
object类型,而是使用具体的对象类型,对对象的属性和方法进行类型检查。let person: { name: string; age: number } = { name: "John", age: 30 };
# 结构化对象
-
// 使用「类型 + 方括号」来表示数组 let fibonacci: number[] = [1, 1, 2, 3, 5]; // 使用数组泛型来表示数组 let fibonacci: Array<number> = [1, 1, 2, 3, 5]; -
Array合并相同类型的对象,而Tuple合并不同类型的对象。Tuple有固定的长度,一旦创建,其长度不能更改。let tom: [string, number] = ['Tom', 25];
# 枚举对象
-
枚举类型用于取值被限定在一定范围内的场景,比如一周只能有七天,颜色限定为红绿蓝等。
enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat }; let day: Days = Days.Mon;
# 高级类型
# 类型组合
Union Types (opens new window)
联合类型表示取值可以为多种类型中的一种。
let myFavoriteNumber: string | number; myFavoriteNumber = 'seven'; myFavoriteNumber = 7;Intersection Types
除了联合 (opens new window)之外,TypeScript 还有交集 (opens new window)。
# 类型抽象
Type Aliases (opens new window)
类型复用机制。
type Point = { x: number; y: number; }; let pt = { x: 100, y: 100 }; type Easing = "ease-in" | "ease-out" | "ease-in-out"; let easing: Easing = "ease-in";Literal Types (opens new window)
精确值类型约束。
let myFavoriteString: "abc" | "def";
# 函数类型
-
function sum(x: number, y: number): number { return x + y; } -
let mySum: (x: number, y: number) => number = function (x: number, y: number): number { return x + y; };
# 类型操作
# 类型推断
# 类型断言
# 类型导入
import type- Type-Only Imports and Export (opens new window)
- Type-Only Imports and Export (opens new window)
- Do I need to use the "import type" feature of TypeScript 3.8 if all of my imports are from my own file? (opens new window)
- What's the difference between import type { X } vs. { type X } (opens new window)
import type { UploadProps, UploadFile, UploadFiles } from "element-plus";
# 类型推断
Promise
提取异步函数返回值的类型。
// 定义返回对象类型 interface _InvoiceData { date: string; number: string; height: number; } // 定义函数类型 type ExtractInvoiceDataFunction = (file: File) => Promise<_InvoiceData>; // 使用 Awaited 和 ReturnType type InvoiceData = Awaited<ReturnType<ExtractInvoiceDataFunction>>; // 如果 TypeScript 版本较低(<4.5),可自定义条件类型 type ExtractPromiseType<T> = T extends Promise<infer U> ? U : T; type InvoiceData = ExtractPromiseType<ReturnType<ExtractInvoiceDataFunction>>;
# 二、工程配置
tsconfig.json (opens new window) 是 TypeScript 项目的配置文件,用于配置 TypeScript 编译器的行为以及项目的类型检查选项。
# 配置文件结构
{
"compilerOptions": { ... },
"include": [ ... ],
"exclude": [ ... ]
}
# 编译选项
# 核心编译策略
- target (opens new window):指定 TS 编译为 ES 的版本
- module (opens new window):指定使用的模块化规范
- strict (opens new window):严格模式总开关
- allowJs (opens new window):允许在项目中导入 JavaScript 文件,而不仅仅是
.ts和.tsx文件 - include (opens new window):指定需要编译的 TS 文件
- exclude (opens new window):指定解析
include时应跳过的文件
# 类型检查策略
- noImplicitAny (opens new window):禁止隐式
any - strictNullChecks (opens new window):空值检查
- lib (opens new window):TypeScript 包含一组内置 JS API 的默认类型定义,以及浏览器环境中(如文档)的类型定义
# 模块解析策略
# 产出物控制
- sourceMap (opens new window):调试映射
- outDir (opens new window):输出目录
- declaration (opens new window):生成
.d.ts
# 三、开发环境
Node.js 默认不支持直接执行 .ts 文件,需要配置开发环境进行转译执行。
# ts-node
可以使用 ts-node 直接运行。
安装依赖:
ts-node(opens new window),typescript(opens new window)npm install -g ts-node typescript # 对于项目级使用,建议本地安装 npm install --save-dev ts-node typescript配置编译规则
在项目根目录初始化
tsconfig.json。tsc --init执行 TypeScript 文件
ts-node test.ts
# tsx
可以使用 tsx (opens new window) 直接运行。
npm i -D tsx
npx tsx src/index.ts